﻿using Pfz.Threading.Disposers;

namespace Pfz.Threading
{
	/// <summary>
	/// A reader writer lock that uses Yield if it does not have the lock. If the locks are held for to much time, this is time consuming.
	/// In my general tests, it is about 10 times faster than ReaderWriterLockSlim class.
	/// </summary>
	public sealed class YieldReaderWriterLock
	{
		#region Fields
			internal YieldReaderWriterLockSlim _lock;
		#endregion

		#region ReadLock
			/// <summary>
			/// Acquires a read lock that must be used in a using clause.
			/// </summary>
			public YieldReadLock ReadLock()
			{
				_lock.EnterReadLock();
				return new YieldReadLock(this);
			}
		#endregion
		#region UpgradeableLock
			/// <summary>
			/// Acquires a upgradeable read lock that must be used in a using clause.
			/// </summary>
			public YieldUpgradeableLock UpgradeableLock()
			{
				_lock.EnterUpgradeableLock();
				return new YieldUpgradeableLock(this);
			}
		#endregion
		#region WriteLock
			/// <summary>
			/// Acquires a write lock that must be used in a using clause.
			/// If you are using a UpgradeableLock use the Upgrade method of the
			/// YieldUpgradeableLock instead or you will cause a dead-lock.
			/// </summary>
			public YieldWriteLock WriteLock()
			{
				_lock.EnterWriteLock();
				return new YieldWriteLock(this);
			}
		#endregion
	}
}
